package com.cgsd.heyu.ui.task;

import android.content.Context;
import android.content.Intent;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.cgsd.heyu.R;
import com.cgsd.heyu.api.ApiService;
import com.cgsd.heyu.common.Constants;
import com.cgsd.heyu.entity.EventMessage;
import com.cgsd.heyu.entity.FlowerInfoEntity;
import com.cgsd.heyu.http.BaseResponse;
import com.cgsd.heyu.http.BaseRxSubscribe;
import com.cgsd.heyu.http.ErrorMessage;
import com.cgsd.heyu.http.RetrofitServiceManager;
import com.cgsd.heyu.http.RetrofitServiceManagerPhp;
import com.cgsd.heyu.http.RxjavaHelper;
import com.cgsd.heyu.presenter.BasePresenter;
import com.cgsd.heyu.ui.BaseActivity;
import com.cgsd.heyu.ui.task.adapter.PayTypeAdapter;
import com.cgsd.heyu.ui.task.vo.PayTypeVo;
import com.cgsd.heyu.ui.task.vo.WxPayVo;
import com.cgsd.heyu.utils.ALiPayUtil;
import com.cgsd.heyu.utils.RequestParams;
import com.cgsd.heyu.utils.WXPayUtil;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import okhttp3.RequestBody;

/**
 * Author: sky on 2021/3/26 10:16
 * Email: xcode126@126.com
 * Desc: 支付界面
 */
public class PayActivity extends BaseActivity<BasePresenter> implements View.OnClickListener {

    private RecyclerView mRecyclerView;

    private TextView tvPrice;
    private TextView tvBalance;
    private TextView tvPay;
    private String oid;
    private double price;

    private PayTypeAdapter typeAdapter;

    public static Intent getIntent(Context context, String oid, double price) {
        return new Intent(context, PayActivity.class).putExtra("oid", oid).putExtra("price", price);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_pay;
    }

    @Override
    protected void initView() {
        oid = getIntent().getStringExtra("oid");
        price = getIntent().getDoubleExtra("price", 0);
        bindViews();

        initAdapter();
    }

    /**
     * init adapter
     */
    private void initAdapter() {
        typeAdapter = new PayTypeAdapter();
        mRecyclerView.setAdapter(typeAdapter);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        typeAdapter.setOnItemClickListener((adapter, view, position) -> {
            typeAdapter.setSelected(position);
        });
    }

    /**
     * bind views
     */
    private void bindViews() {
        mRecyclerView = findViewById(R.id.mRecyclerView);
        tvPrice = findViewById(R.id.tv_price);
        tvBalance = findViewById(R.id.tv_balance);
        tvPay = findViewById(R.id.tv_pay);
        tvPay.setOnClickListener(this);
        tvPrice.setText(String.format("%1$s%2$.2f", "￥", price));
    }

    @Override
    protected void initData() {
        getFlowerInfo();
        getPayType();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_pay:
                int selected = typeAdapter.getSelected();
                if (selected == -1) {
                    showToast("暂未选择可支付方式");
                    return;
                }
                getPayData(oid, selected);
                break;
        }
    }

//    private int getTypeParam(int id){
//
//    }

    /**
     * get Task list
     */
    public void getPayType() {
        showLoading();
        RetrofitServiceManagerPhp.getInstance().creat(ApiService.class)
                .getPayType()
                .compose(RxjavaHelper.observeOnMainThread())
                .subscribe(new BaseRxSubscribe<BaseResponse<List<PayTypeVo>>>() {
                    @Override
                    public void onSuccess(BaseResponse<List<PayTypeVo>> baseResponse) {
                        processType(baseResponse.getBizBody());
                        loadSuccess();
                    }

                    @Override
                    public void onError(ErrorMessage error) {
                        setErrorMessage(error);
                        loadSuccess();
                    }
                });
    }

    /**
     * 处理支付方式
     *
     * @param list
     */
    private void processType(List<PayTypeVo> list) {
        List<PayTypeVo> payList = new ArrayList<>();
        if (list != null && list.size() > 0) {
            for (PayTypeVo typeVo : list) {
                if (typeVo.state == 1) {
                    payList.add(typeVo);
                }
            }
        }
        typeAdapter.setNewData(payList);
    }

    /**
     * 获取支付数据
     *
     * @param oid
     */
    private void getPayData(String oid, int type) {
        showCommonSubmitDialog();
        RequestBody requestBody = new RequestParams().put("oid", oid).put("type", type).get();
        RetrofitServiceManagerPhp.getInstance().creat(ApiService.class)
                .getPayData(requestBody)
                .compose(RxjavaHelper.observeOnMainThread())
                .subscribe(new BaseRxSubscribe<BaseResponse<String>>() {
                    @Override
                    public void onSuccess(BaseResponse<String> response) {
                        dismissCommonSubmitDialog();
                        if (response.getCode() == Constants.SUCCESS_CODE) {
                            processPayData(response.getBizBody());
                        } else {
                            showToast(response.getResultMsg());
                        }
                    }

                    @Override
                    public void onError(ErrorMessage error) {
                        setErrorMessage(error);
                    }
                });
    }

    /**
     * process pay data
     *
     * @param orderInfo
     */
    private void processPayData(String orderInfo) {
        if (TextUtils.isEmpty(orderInfo)){
            showToast(getString(R.string.a_config_error_tip));
            return;
        }
        switch (typeAdapter.getSelected()) {
            case 0://钱包
                break;
            case 1://支付宝
                new ALiPayUtil(PayActivity.this, orderInfo, isSuccess -> {
                    showToast(isSuccess ? "支付成功" : "支付失败");
                    EventBus.getDefault().post(new EventMessage<>(Constants.EventCode.MY_PUBLISH_REFRESH));
                    finish();
                });
                break;
            case 2://微信
                try {
                    String replace = orderInfo.replace("package", "packageX");
                    WxPayVo wxPayVo = new Gson().fromJson(replace, WxPayVo.class);
                    new WXPayUtil(this, wxPayVo, "orderPay");
                } catch (JsonSyntaxException e) {
                    showToast(getString(R.string.a_config_error_tip));
                }
                break;
            default:
        }
    }

    /**
     * 获取积分信息
     */
    public void getFlowerInfo() {
        showLoading();
        RequestBody requestBody = new RequestParams().putUserId().get();
        RetrofitServiceManager.getInstance().creat(ApiService.class)
                .getFlowerInfo(requestBody)
                .compose(RxjavaHelper.observeOnMainThread())
                .subscribe(new BaseRxSubscribe<BaseResponse<FlowerInfoEntity>>() {
                    @Override
                    public void onSuccess(BaseResponse<FlowerInfoEntity> baseResponse) {
                        loadSuccess();
                        processFlowerInfo(baseResponse);
                    }

                    @Override
                    public void onError(ErrorMessage error) {
                        loadSuccess();
                        setErrorMessage(error);
                    }
                });
    }

    /**
     * 处理积分信息
     *
     * @param baseResponse
     */
    private void processFlowerInfo(BaseResponse<FlowerInfoEntity> baseResponse) {
        FlowerInfoEntity bizBody = baseResponse.getBizBody();
        if (bizBody != null) {
            tvBalance.setText(Html.fromHtml(String.format("%1$s<font color ='#33B9CC'>%2$s</font>%3$s", "(", bizBody.usableAmount, "积分)")));
        } else {
            showToast(baseResponse.getResultMsg());
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(EventMessage event) {
        if (event.getCode() == Constants.EventCode.MY_PUBLISH_REFRESH) {
           finish();
        }
    }
}
